import React, { useState } from 'react';
import { Table } from 'antd';

import Pagination from '@/components/Pagination';

const TableWrapper = ({ columns, dataSource, tablePageChange, pagination, ...tableProps }) => (
    <div>
        <Table
            columns={columns}
            rowKey="id"
            dataSource={dataSource}
            pagination={false}
            scroll={{ x: 'max-content' }}
            bordered
            {...tableProps}
        />
        <Pagination {...pagination} onChange={tablePageChange} />
    </div>
);

const useTableWrapper = () => {
    const [dataSource, setDataSource] = useState([]);
    const [pagination, setPagination] = useState({ current: 1, pageSize: 10 });

    const tablePageChange = search => ({ current, pageSize }) => {
        search({
            current,
            pageSize
        });
    };

    return {
        dataSource,
        pagination,
        setDataSource,
        setPagination,
        render({ columns, search, tableProps }) {
            return (
                <TableWrapper
                    columns={columns}
                    dataSource={dataSource}
                    tablePageChange={tablePageChange(search)}
                    pagination={pagination}
                    {...tableProps}
                />
            );
        }
    };
};

export default useTableWrapper;
